/**
 * 这个脚本用于创建过期和撤销状态的凭证示例
 */
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3001';
const SERVER_DATA_DIR = path.join(__dirname, '../server/data');
const WALLET_CREDENTIALS_FILE = path.join(SERVER_DATA_DIR, 'wallet', 'credentials.json');
const ISSUER_CREDENTIALS_FILE = path.join(SERVER_DATA_DIR, 'issuer', 'issued_credentials.json');

// 加载现有凭证
function loadCredentials(filePath) {
  try {
    if (fs.existsSync(filePath)) {
      const data = fs.readFileSync(filePath, 'utf-8');
      if (data) {
        return JSON.parse(data);
      }
    }
  } catch (error) {
    console.error(`加载凭证失败: ${filePath}`, error);
  }
  return [];
}

// 保存凭证
function saveCredentials(filePath, data) {
  try {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
    console.log(`保存凭证成功: ${filePath}`);
  } catch (error) {
    console.error(`保存凭证失败: ${filePath}`, error);
  }
}

// 生成过期凭证
function createExpiredCredentials(baseCredentials) {
  const expired = [];
  
  // 创建过期的学位证书
  const expiredDegree = JSON.parse(JSON.stringify(baseCredentials[0][1]));
  expiredDegree.id = `urn:uuid:${uuidv4()}`;
  expiredDegree.credential.id = expiredDegree.id;
  expiredDegree.issuanceDate = new Date(Date.now() - 400 * 24 * 60 * 60 * 1000).toISOString(); // 400天前发行
  expiredDegree.expirationDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(); // 30天前过期
  expiredDegree.credential.issuanceDate = expiredDegree.issuanceDate;
  expiredDegree.credential.expirationDate = expiredDegree.expirationDate;
  expiredDegree.credential.credentialSubject.degree.name = "过期学士学位";
  expired.push([expiredDegree.id, expiredDegree]);

  // 创建过期的专业证书
  const expiredCert = JSON.parse(JSON.stringify(baseCredentials[2][1]));
  expiredCert.id = `urn:uuid:${uuidv4()}`;
  expiredCert.credential.id = expiredCert.id;
  expiredCert.issuanceDate = new Date(Date.now() - 500 * 24 * 60 * 60 * 1000).toISOString(); // 500天前发行
  expiredCert.expirationDate = new Date(Date.now() - 100 * 24 * 60 * 60 * 1000).toISOString(); // 100天前过期
  expiredCert.credential.issuanceDate = expiredCert.issuanceDate;
  expiredCert.credential.expirationDate = expiredCert.expirationDate;
  expiredCert.credential.credentialSubject.certificationName = "过期AWS认证";
  expired.push([expiredCert.id, expiredCert]);

  return expired;
}

// 生成撤销凭证
function createRevokedCredentials(baseCredentials) {
  const revoked = [];
  
  // 创建撤销的学位证书
  const revokedDegree = JSON.parse(JSON.stringify(baseCredentials[1][1]));
  revokedDegree.id = `urn:uuid:${uuidv4()}`;
  revokedDegree.credential.id = revokedDegree.id;
  revokedDegree.issuanceDate = new Date(Date.now() - 200 * 24 * 60 * 60 * 1000).toISOString(); // 200天前发行
  revokedDegree.expirationDate = new Date(Date.now() + 165 * 24 * 60 * 60 * 1000).toISOString(); // 还有165天过期
  revokedDegree.credential.issuanceDate = revokedDegree.issuanceDate;
  revokedDegree.credential.expirationDate = revokedDegree.expirationDate;
  revokedDegree.credential.credentialSubject.degree.name = "已撤销硕士学位";
  revokedDegree.revoked = true; // 标记为已撤销
  revoked.push([revokedDegree.id, revokedDegree]);

  // 创建撤销的技能凭证
  const revokedSkill = JSON.parse(JSON.stringify(baseCredentials[4][1]));
  revokedSkill.id = `urn:uuid:${uuidv4()}`;
  revokedSkill.credential.id = revokedSkill.id;
  revokedSkill.issuanceDate = new Date(Date.now() - 150 * 24 * 60 * 60 * 1000).toISOString(); // 150天前发行
  revokedSkill.expirationDate = new Date(Date.now() + 215 * 24 * 60 * 60 * 1000).toISOString(); // 还有215天过期
  revokedSkill.credential.issuanceDate = revokedSkill.issuanceDate;
  revokedSkill.credential.expirationDate = revokedSkill.expirationDate;
  revokedSkill.credential.credentialSubject.skillName = "已撤销前端开发技能";
  revokedSkill.revoked = true; // 标记为已撤销
  revoked.push([revokedSkill.id, revokedSkill]);

  return revoked;
}

// 主函数
async function main() {
  try {
    // 确保目录存在
    if (!fs.existsSync(path.join(SERVER_DATA_DIR, 'wallet'))) {
      fs.mkdirSync(path.join(SERVER_DATA_DIR, 'wallet'), { recursive: true });
    }
    if (!fs.existsSync(path.join(SERVER_DATA_DIR, 'issuer'))) {
      fs.mkdirSync(path.join(SERVER_DATA_DIR, 'issuer'), { recursive: true });
    }

    // 加载现有钱包凭证
    const walletCredentials = loadCredentials(WALLET_CREDENTIALS_FILE) || [];
    if (!walletCredentials || walletCredentials.length === 0) {
      console.error('没有找到现有凭证，请先加载示例凭证');
      process.exit(1);
    }
    
    console.log(`找到 ${walletCredentials.length} 个现有凭证`);

    // 生成过期凭证
    const expiredCredentials = createExpiredCredentials(walletCredentials);
    console.log(`创建了 ${expiredCredentials.length} 个过期凭证`);

    // 生成撤销凭证
    const revokedCredentials = createRevokedCredentials(walletCredentials);
    console.log(`创建了 ${revokedCredentials.length} 个撤销凭证`);

    // 合并所有凭证
    const allCredentials = [
      ...walletCredentials,
      ...expiredCredentials,
      ...revokedCredentials
    ];

    // 保存到钱包凭证文件
    saveCredentials(WALLET_CREDENTIALS_FILE, allCredentials);
    
    // 同时保存到发行方凭证文件（如果存在）
    if (fs.existsSync(ISSUER_CREDENTIALS_FILE)) {
      const issuerCredentials = loadCredentials(ISSUER_CREDENTIALS_FILE) || [];
      
      // 将新创建的凭证添加到发行方凭证中
      [...expiredCredentials, ...revokedCredentials].forEach(([id, cred]) => {
        const issuerCred = {
          credential: cred.credential,
          id: cred.credential.id,
          holderDID: cred.credential.credentialSubject.id,
          issuerDID: cred.credential.issuer,
          status: cred.revoked ? "revoked" : "active",
          issuanceDate: cred.issuanceDate,
          expirationDate: cred.expirationDate,
          revoked: cred.revoked
        };
        
        issuerCredentials.push([id, issuerCred]);
      });
      
      saveCredentials(ISSUER_CREDENTIALS_FILE, issuerCredentials);
      console.log(`更新了发行方凭证记录`);
    }

    console.log('成功创建过期和撤销的凭证示例数据！');
  } catch (error) {
    console.error('生成特殊凭证示例数据时出错:', error);
  }
}

// 执行主函数
main(); 